package com.example.lotterysystem.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {

    private final static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    /**
     * StringRedisTemplate继承RedisTemplate<String, String>，bytes[] 两种的区别仅仅是序列化⽅式不⼀样。
     * 这⾥选⽤StringRedisTemplate，能够避免乱码问题。
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置值
     * @param key
     * @param value
     * @return
     */
    public Boolean set(String key,String value) {
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil set({},{})",key,value,e);
            return false;
        }
    }

    /**
     * 设置值(过期时间)
     * @param key
     * @param value
     * @param time
     * @return
     */
    public Boolean set(String key,String value,Long time) {
        try {
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil set({},{},{})",key,value,time,e);
            return false;
        }
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return StringUtils.hasText(key)
                    ? stringRedisTemplate.opsForValue().get(key)
                    : null;
        }catch (Exception e) {
            logger.error("RedisUtil get({})",key,e);
            return null;
        }
    }
    public Boolean del(String... key) {
        try {
            if(null != key && key.length == 1) {
                stringRedisTemplate.delete(key[0]);
            } else {
                stringRedisTemplate.delete(
                        (Collection<String>) CollectionUtils.arrayToList(key)
                );
            }
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil del({})",key,e);
            return false;
        }
    }

    /**
     * 判斷key是否存在
     *
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        try {
            return StringUtils.hasText(key)
                    ? stringRedisTemplate.hasKey(key)
                    : false;
        }catch (Exception e) {
            logger.error("RedisUtil hasKey({})",key,e);
            return false;
        }

    }

}
